#!/usr/bin/env python3
"""A review of one call for tuning the agent: every card with the operator's reactions, the private asks, and the
stretches of real talk where the agent wrote nothing, so a prompt change can be argued from what happened.

  sidekick-tune [--call <id or prefix>] [--env staging] [--quiet-minutes 3] [--samples 4]

Defaults to the call agent's current (or last) call. Reads calls/<call>/notebook.jsonl (cards, 👍/👎 and reasons,
shares, deletes, actions), calls/<call>/feed.log (what was said, with times), asks.ndjson (the private asks) and
calls/<call>/agent.json (model, effort and the Standing constraints the agent joined with). `sidekick-debug` has
the agent's turn-by-turn reasoning when a card or a silence needs explaining.
"""
import argparse
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import sidekick_context as ctx  # noqa: E402

SPEECH = re.compile(r"^\[(\d{4}-\d\d-\d\dT[^\]]+)\]\s+([A-Z][\w'-]*(?: [A-Z][\w'-]*)+):(.*)$")
FILLER = re.compile(r"^(yeah|yes|yep|no|nope|okay|ok|right|sure|mm+|mhm|uh-huh|um+|uh+|cool|nice|totally|exactly|"
                    r"got it|i see|true|wow|haha|ha|interesting|for sure|oh|ah)[\s,.!?]*$", re.I)


def stamp(ms_or_iso):
    if isinstance(ms_or_iso, (int, float)) or str(ms_or_iso).isdigit():
        return int(ms_or_iso) / 1000
    return datetime.fromisoformat(str(ms_or_iso).replace("Z", "+00:00")).timestamp()


def clock(t, start):
    s = max(0, int(t - start))
    return f"{s // 60}:{s % 60:02d}"


def find_call(arg):
    calls = ctx.SIDEKICK / "calls"
    if not arg:
        arg = ctx.agent_record().get("call")
    if not arg:
        folders = sorted((p for p in calls.glob("*") if (p / "feed.log").exists()), key=lambda p: p.stat().st_mtime)
        arg = folders[-1].name if folders else None
    if not arg:
        sys.exit("sidekick-tune: no call (pass --call)")
    matches = [p.name for p in calls.glob(f"{arg}*") if p.is_dir()]
    if len(matches) != 1:
        sys.exit(f"sidekick-tune: {arg} matches {len(matches)} calls in {calls}")
    return matches[0]


def speech(call):
    out = []
    for raw in (ctx.read(ctx.SIDEKICK / "calls" / call / "feed.log") or "").splitlines():
        line = raw.split("\t", 1)[-1]
        m = SPEECH.match(line)
        if m:
            out.append((stamp(m.group(1)), m.group(2), m.group(3).strip()))
    return sorted(set(out))


def substantive(text):
    return len(text.split()) >= 6 and not FILLER.match(text)


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--call")
    ap.add_argument("--quiet-minutes", type=float, default=3, help="a stretch this long with no card is listed (default 3)")
    ap.add_argument("--samples", type=int, default=4, help="lines shown from each quiet stretch")
    ap.add_argument("--env", choices=ctx.CLIS, help=argparse.SUPPRESS)
    a = ap.parse_args()
    call = find_call(a.call)
    folder = ctx.SIDEKICK / "calls" / call
    events = [json.loads(l) for l in (ctx.read(folder / "notebook.jsonl") or "").splitlines() if l.strip()]
    said = speech(call)
    start = said[0][0] if said else (stamp(events[0]["at"]) if events else 0)
    title = next((e.get("title") for e in events if e.get("type") == "call"), "")

    sessions = ctx.read_json(folder / "agent.json").get("sessions") or []
    print(f"call {call[:8]}  {title}  {datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M') if start else ''}")
    for s in sessions:
        print(f"agent {s.get('id')}  model={s.get('model', '?')} effort={s.get('effort', '?')}")
    if sessions and sessions[-1].get("constraints"):
        print("standing constraints it joined with:")
        for line in sessions[-1]["constraints"].splitlines():
            print(f"  {line[:200]}")

    notes, order = {}, []
    for e in events:
        kind, nid = e.get("type"), e.get("note")
        if kind == "note":
            notes[e["id"]] = {**e, "reactions": [], "revised": 0}
            order.append(e["id"])
        elif kind == "revise" and nid in notes:
            notes[nid].update(title=e.get("title", notes[nid]["title"]), body=e.get("body", notes[nid].get("body")))
            notes[nid]["revised"] += 1
        elif kind == "vote" and nid in notes:
            r = notes[nid]["reactions"]
            mark = "👍" if e.get("vote") == "up" else "👎"
            if e.get("reason"):
                r[:] = [x for x in r if x != mark]
                mark += f" {e['reason']}"
            elif e.get("source") not in (None, "thumb"):
                mark += f" ({e['source']})"
            r.append(mark)
        elif kind == "share" and nid in notes:
            notes[nid]["reactions"].append("shared")
        elif kind == "delete" and nid in notes:
            notes[nid]["reactions"].append("deleted")
        elif kind == "action" and nid in notes and e.get("state") in ("running", "done"):
            notes[nid]["reactions"].append("used its action")

    asks = []
    for raw in (ctx.read(ctx.SIDEKICK / "asks.ndjson") or "").splitlines():
        try:
            rec = json.loads(raw)
        except ValueError:
            continue
        if rec.get("call") == call and rec.get("source", "ask") == "ask" and rec.get("text"):
            asks.append((stamp(rec["at"]) if rec.get("at") else start, " ".join(str(rec["text"]).split())))

    up = sum(any(x.startswith("👍") or x in ("shared", "used its action") for x in n["reactions"]) for n in notes.values())
    down = sum(any(x.startswith("👎") or x == "deleted" for x in n["reactions"]) for n in notes.values())
    minutes = (said[-1][0] - start) / 60 if said else 0
    talk = sum(substantive(t) for _, _, t in said)
    print(f"\n{len(notes)} cards in {minutes:.0f} min ({talk} substantive lines) · {up} liked · {down} disliked · "
          f"{len(notes) - up - down} no reaction · {len(asks)} private asks")

    print("\n=== cards ===")
    for nid in order:
        n = notes[nid]
        t = stamp(n["at"])
        before = [f"{who.split()[0]}: {text}" for tt, who, text in said if t - 90 <= tt <= t and substantive(text)][-2:]
        tags = ", ".join(n["reactions"]) or "no reaction"
        extra = " · running" if n.get("running") in (True, "True") else ""
        extra += f" · revised {n['revised']}×" if n["revised"] else ""
        print(f"\n{clock(t, start)}  [{tags}]  {n.get('title', '')}{extra}")
        body = " ".join(str(n.get("body") or "").split())
        if body:
            print(f"      {body[:400]}{'…' if len(body) > 400 else ''}")
        for b in before:
            print(f"      ← {b[:160]}")
    if asks:
        print("\n=== private asks ===")
        for t, text in asks:
            print(f"{clock(t, start)}  {text}")

    cards = sorted(stamp(notes[n]["at"]) for n in order) + [stamp(e["at"]) for e in events if e.get("type") == "revise"]
    cards.sort()
    edges = [start] + cards + [said[-1][0] if said else start]
    print(f"\n=== quiet stretches (≥ {a.quiet_minutes:g} min of talk with no card) ===")
    shown = 0
    for lo, hi in zip(edges, edges[1:]):
        if hi - lo < a.quiet_minutes * 60:
            continue
        lines = [(t, who, text) for t, who, text in said if lo < t < hi and substantive(text)]
        if len(lines) < 5:
            continue
        shown += 1
        print(f"\n{clock(lo, start)}–{clock(hi, start)}  {(hi - lo) / 60:.0f} min, {len(lines)} substantive lines")
        step = max(1, len(lines) // a.samples)
        for t, who, text in lines[::step][: a.samples]:
            print(f"      {clock(t, start)} {who.split()[0]}: {text[:170]}")
    if not shown:
        print("(none)")
    print(f"\nwhy it passed: sidekick-debug --call {call[:8]} --agent-only")
    return 0


if __name__ == "__main__":
    sys.exit(main())
